package com.iptv.grape.domain;

import com.google.gson.Gson;
import com.iptv.grape.event.msg.Asset;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ReadJsonFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

// 资产播放历史集合
public class AssetPlayDataList {
    private List<AssetPlayData> assets;

    public List<AssetPlayData> getAssets() {
        return assets;
    }

    public void setAssets(List<AssetPlayData> assets) {
        this.assets = assets;
    }


    // 是否为空
    public boolean isEmpty(){
        return this.assets == null;
    }

    // 初始化
    public void init(){
        this.assets = new ArrayList<AssetPlayData>();
    }
    // 根据传递过来的参数来直接查找当前是否存在有播放历史
    public AssetPlayData find(Asset asset){
        for(int i = 0; i < this.assets.size(); i++){
            AssetPlayData assetData = assets.get(i);
            if(assetData.getAssetID().equals(asset.getAssetID())){
                assetData.setPlayUrl(asset.getPlayUrl());
                assetData.setSubAssetID(asset.getSubAssetID());
                return assetData;
            }
        }
        AssetPlayData data = AssetPlayData.toAssetPlayData(asset);
        this.assets.add(data);
        this.serializeToFile();
        return data;
    }

    // 根据资源ID查找
    public AssetPlayData find(String assetID){
        for(int i = 0; i < this.assets.size(); i++){
            AssetPlayData assetData = assets.get(i);
            if(assetData.getAssetID().equals(assetID)){
                return assetData;
            }
        }
        return null;
    }

    public List<AssetPlayData> getAll(){
        return this.assets;
    }

    public String toJson(){

        Gson gson = new Gson();
        String json = gson.toJson(this);
        return json;
    }

    // 序列化到文件
    public synchronized void serializeToFile(){
        String json = this.toJson();
        ReadJsonFile.writeFile("assetsHis.json",json);
        AppLog.getCurLog().out("序列化点播历史到文件");
    }

    // 反序列化对象
    public static AssetPlayDataList unSerializeToFile(){

        AssetPlayDataList assets = new AssetPlayDataList();
        try {
            if(ReadJsonFile.fileExists("assetsHis.json")) {
                String json = ReadJsonFile.readFile("assetsHis.json");
                assets = new Gson().fromJson(json, AssetPlayDataList.class);
            }
            return assets;
        }
        catch (Exception ex){
            ex.printStackTrace();
            return assets;
        }

    }
}
